#include "OS.h"
#include <windows.h>

using namespace host;

void OS::SleepMS(UInt32 ms)
{
    ::Sleep(ms);
}

void OS::Sleep(UInt32 sec)
{
    ::Sleep(sec * 1000);
}

int OS::GetErrno()
{
    int winErr = ::GetLastError();

    // Convert to a POSIX errorcode. The *major* assumption is that
    // the meaning of these codes is 1-1 and each Winsock, etc, etc
    // function is equivalent in errors to the POSIX standard. This is 
    // a big assumption, but the server only checks for a small subset of
    // the real errors, on only a small number of functions, so this is probably ok.
    switch (winErr)
    {
        case ERROR_FILE_NOT_FOUND: return ENOENT;
        case ERROR_PATH_NOT_FOUND: return ENOENT;
        case WSAEINTR:      return EINTR;
        case WSAENETRESET:  return EPIPE;
        case WSAENOTCONN:   return ENOTCONN;
        case WSAEWOULDBLOCK:return EAGAIN;
        case WSAECONNRESET: return EPIPE;
        case WSAEADDRINUSE: return EADDRINUSE;
        case WSAEMFILE:     return EMFILE;
        case WSAEINPROGRESS:return EINPROGRESS;
        case WSAEADDRNOTAVAIL: return EADDRNOTAVAIL;
        case WSAECONNABORTED: return EPIPE;
        case 0:             return 0;

        default:            return ENOTCONN;
    }

}


unsigned short OS::Ntohs(unsigned short val)
{
    return (val >> 8) | (val << 8);
}

unsigned int OS::Ntohl(unsigned int val)
{
    return Ntohs(val >> 16) | (Ntohs(val) << 16);
}
